package com.mpgame.managers;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import com.mpgame.database.mysql.model.game.SceneInfo;
import com.mpgame.database.mysql.service.game.SceneInfoService;
import com.mpgame.models.GameScene;
import com.mpgame.utils.Log;

public class SceneManager {
    private static volatile SceneManager instance;
    /** 场景ID -> 场景实例 */
    private final Map<String, GameScene> scenes = new ConcurrentHashMap<>();
    /**  玩家ID -> 场景ID */
    private final Map<Integer, String> playerSceneMap = new ConcurrentHashMap<>();

    private SceneManager() {
        initialize();
    }

    public static SceneManager getInstance() {
        if (instance == null) {
            synchronized (SceneManager.class) {
                if (instance == null) {
                    instance = new SceneManager();
                }
            }
        }
        return instance;
    }
    private void initialize(){
        SceneInfoService svc = new SceneInfoService();
        for(SceneInfo sceneInfo : svc.getAllSceneInfos()){
            Log.info("已添加场景" + sceneInfo.getName() + ":" + sceneInfo.getSceneName());
            scenes.put(sceneInfo.getSceneName(), new GameScene(sceneInfo.getName(), sceneInfo.getSceneName()));
        }
    }

    // 玩家进入场景
    public boolean enterScene(int playerId, String sceneName) {
        // 检查场景是否存在
        GameScene scene = scenes.get(sceneName);
        if(scene == null) return false;

        // 检查场景人数限制
        if (scene.getPlayerCount() >= scene.getMaxPlayers()) 
            return false; // 场景已满
        if(scene.hasPlayer(playerId))
            return false; // 玩家已经在此场景中了

        // 玩家离开原场景
        leaveCurrentScene(playerId);

        // 加入新场景
        scene.addPlayer(playerId);
        playerSceneMap.put(playerId, sceneName);

        return true;
    }
    private void leaveCurrentScene(int playerId) {
        String currentSceneName = playerSceneMap.remove(playerId);
        if (currentSceneName != null) {
            GameScene scene = scenes.get(currentSceneName);
            if (scene != null) {
                scene.removePlayer(playerId);
            }
        }
    }

    // 获取场景内所有玩家
    public Set<Integer> getScenePlayers(String sceneName) {
        GameScene scene=scenes.get(sceneName);
        if(scene != null)
            return scene.getPlayers();
        return null;
    }
}
